﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CoreAudioApi;
using DukeySoundHelper.API;
using DukeySoundHelper.Properties;
using System.Runtime.InteropServices;
using MHook;

namespace DukeySoundHelper
{
    public partial class MainFrm : Form
    {
        private MMDevice device;
        ShowVolumnFrm frm = new ShowVolumnFrm();

        public MainFrm()
        {
            InitializeComponent();
        }
        private void MainFrm_Load(object sender, EventArgs e)
        {
            InitConfig();

            OperatingSystem os = Environment.OSVersion;
            //if (os.Version.Major.ToString()) ;
            switch (os.Version.Major)
            {
                    //win7系统
                case 6:
                    {
                        MMdeviceWin7();
                        //注册热键
                        if (MyConfig.Instance.CanUseHotKeys)
                        {
                            RegisterHotKeys();
                            //MouseCase1();
                        }
                        //注册鼠标键
                        if (MyConfig.Instance.CanUseMouseKeys)
                        {
                            //RegisterMouseKeys();
                        }
                        break;
                    }
            }
           // this.Visible = false;
        }

        #region 加载音量控制api win7版
        private void MMdeviceWin7()
        {
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            tbMaster.Value = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
            label1.Text = "  " + tbMaster.Value;
            device.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);
        }
        

        private void AudioEndpointVolume_OnVolumeNotification(AudioVolumeNotificationData data)
        {
            if (this.InvokeRequired)
            {
                object[] Params = new object[1];
                Params[0] = data;
                this.Invoke(new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification), Params);
            }
            else
            {
                tbMaster.Value = (int)(Math.Round(data.MasterVolume, 2) * 100);
                label1.Text = " " + tbMaster.Value;
            }
        }
        private void tbMaster_Scroll(object sender, EventArgs e)
        {            
            device.AudioEndpointVolume.MasterVolumeLevelScalar = (float)Math.Round(((decimal)tbMaster.Value / 100), 2);
            
            if (this.Visible == true && isfullScreen == false)
            {
                frm.timer1.Interval = MyConfig.Instance.Waitseconds * 1000;
                frm.timer1.Enabled = false;
                frm.panel1.Width = tbMaster.Value * 6;
                frm.label1.Text = "音量" + tbMaster.Value + "%";
                frm.label2.Text = DateTime.Now.ToString("HH:mm");

                frm.panel1.BackColor = DukeyComm.ToColor(MyConfig.Instance.BackColor);
                if (!(MyConfig.Instance.WinPopLeft == -1 && MyConfig.Instance.WinPopTop == -1))
                {
                    frm.Location = new Point(MyConfig.Instance.WinPopLeft, MyConfig.Instance.WinPopTop);
                }
                else
                {
                    frm.StartPosition = FormStartPosition.CenterScreen;
                }
                frm.Show();
                frm.timer1.Enabled = true;
            }
        }
        #endregion

        #region 菜单功能
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
         
            HotKey.UnregisterHotKey(Handle, 100);//卸载第1个快捷键         
            HotKey.UnregisterHotKey(Handle, 200); //缷载第2个快捷键
            HotKey.UnregisterHotKey(Handle, 300); //缷载第2个快捷键
            RegisterAppBar(true);//取消注册全屏钩子
            Environment.Exit(0);
        }

        private void 高级设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigFrm frm = new ConfigFrm();
            frm.ShowDialog();
        }

        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            //notifyIcon1.ShowBalloonTip(3000, "fsfds", "ggg",ToolTipIcon.None);
            //MessageBox.Show(sender.GetType().ToString());
            //if (e.Button == MouseButtons.Left)
            //{
            //    MessageBox.Show(e.X.ToString());
            //    contextMenuStrip2.Show(new Point(e.X, e.Y));
            //}
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                
                contextMenuStrip2.Show(Cursor.Position.X-20,Cursor.Position.Y);
                ShowInTaskbar = false;
            }
        }
        #endregion

        #region 加载配置文件
        private void InitConfig()
        {
            //读取资源文件
            MyConfig.Instance.AutoStart = Settings.Default.autostart;
            MyConfig.Instance.IsMouseLeft = Settings.Default.IsMouseLeft;
            MyConfig.Instance.IsMouseRight = Settings.Default.IsMouseRight;
            MyConfig.Instance.Highkey = Settings.Default.Highkey;
            MyConfig.Instance.Lowkey = Settings.Default.Lowkey;
            MyConfig.Instance.ChangeUnit = Settings.Default.ChangeUnit;
            MyConfig.Instance.BackColor = Settings.Default.backcolor;
            MyConfig.Instance.Waitseconds = Settings.Default.waitseconds;
            MyConfig.Instance.WinPopLeft = Settings.Default.WinPopLeft;
            MyConfig.Instance.WinPopTop = Settings.Default.WinPopTop;

            //MyConfig.Instance.Highkeys = Settings.Default.Highkey;
        }
        #endregion        

        #region 检查全屏
        int uCallBackMsg = 0;//检查全屏
        private void RegisterAppBar(bool registered)
        {
            APPBARDATA abd = new APPBARDATA();
            abd.cbSize = Marshal.SizeOf(abd);
            abd.hWnd = this.Handle;
            if (!registered)
            {
                //register  
                uCallBackMsg = APIWrapper.RegisterWindowMessage("APPBARMSG_CSDN_HELPER");
                abd.uCallbackMessage = uCallBackMsg;
                uint ret = APIWrapper.SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
            }
            else
            {
                APIWrapper.SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
            }
        }
        bool isfullScreen = false;

        #endregion

        KeyboardHook kh=new KeyboardHook();

        #region 注册热键
        public void RegisterHotKeys()
        {
           // MHook.Hook h = new Hook();

            kh.KeyUp += new KBEventHandler(kh_KeyUp);
            kh.KeyDown+=new KBEventHandler(kh_KeyDown);
            kh.Hook();
            //HotKey.RegisterHotKey(Handle, 100,DukeyComm.ConvertToZhuheKey(MyConfig.Instance.Highkeys.Key), MyConfig.Instance.Highkeys.Value); //定义热键为Alt+Tab，这里实现了屏幕系统Alt+Tab键             
            //HotKey.RegisterHotKey(Handle, 200, DukeyComm.ConvertToZhuheKey(MyConfig.Instance.Lowkeys.Key), MyConfig.Instance.Lowkeys.Value); //注册2个热键,根据id值100,200来判断需要执行哪个函数
            //HotKey.RegisterHotKey(Handle, 300, DukeyComm.ConvertToZhuheKey(MyConfig.Instance.Mutekeys.Key), MyConfig.Instance.Mutekeys.Value); //注册2个热键,根据id值100,200来判断需要执行哪个函数
        }

        bool kh_KeyUp(Keys key)
        {
            if (key == Keys.ControlKey)
            {
            }
            return false;
        }

        bool kh_KeyDown(Keys key)
        {
            //MessageBox.Show(key.ToString());

            return false;
        }

        void hm_HotkeyUp(string hotkeyName)
        {
            MessageBox.Show(hotkeyName);
        }
        protected override void WndProc(ref Message m)//监视Windows消息       
        {
            const int WM_HOTKEY = 0x0312;//如果m.Msg的值为0x0312那么表示用户按下了热键       
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    ProcessHotkey(m);//按下热键时调用ProcessHotkey()函数              
                    break;
            }
            if (m.Msg == uCallBackMsg)
            {
                switch (m.WParam.ToInt32())
                {
                    case (int)ABNotify.ABN_FULLSCREENAPP:
                        {
                            if ((int)m.LParam == 1)
                                this.isfullScreen = true;
                            else
                                this.isfullScreen = false;
                            break;
                        }
                    default:
                        break;
                }
            }
            base.WndProc(ref m); //将系统消息传递自父类的WndProc    
        }

        private void ProcessHotkey(Message m) //按下设定的键时调用该函数       
        {
            IntPtr id = m.WParam; //IntPtr用于表示指针或句柄的平台特定类型            //MessageBox.Show(id.ToString());       
            string sid = id.ToString();
            int change = MyConfig.Instance.ChangeUnit;
            switch (sid)
            {
                case "100":
                    {
                        //device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)tbMaster.Value / 100.0f);

                        if ((tbMaster.Value + change) > 100)
                            tbMaster.Value = 100;
                        else
                        {
                            tbMaster.Value += change;
                            if (tbMaster.Value == 29)
                                tbMaster.Value = 30;
                        }
                        //label1.Text = "主音量 " + tbMaster.Value;
                        this.Invoke(new EventHandler(tbMaster_Scroll));
                    }
                    break;

                case "200":
                    {
                        if ((tbMaster.Value - change) < 0)
                            tbMaster.Value = 0;
                        else
                        {
                            tbMaster.Value -= change;
                        }
                        //label1.Text = "主音量 " + tbMaster.Value;
                        this.Invoke(new EventHandler(tbMaster_Scroll));
                    }
                    break;

                case "300"://静音
                    device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
                    break;
            }
            //GC.Collect();
        }


        #endregion

        MouseHook mh1 = new MouseHook();
        /// <summary>
        /// 第一种情况,按住鼠标左键 +滚轮向上
        /// </summary>
        private void MouseCase1()
        {            
            mh1.MouseButtonDown += new MouseHookEventHandler(mh1_MouseButtonDown);
            mh1.MouseButtonUp += new MouseHookEventHandler(mh1_MouseButtonUp);
        }

        bool mh1_MouseButtonUp(MouseHookEventArgs e)
        {
            mh1.MouseWheelDown += new MouseHookEventHandler(mh1_MouseWheelDown);
            mh1.MouseWheelUp += new MouseHookEventHandler(mh1_MouseWheelUp);
            return true;
        }

        bool mh1_MouseWheelUp(MouseHookEventArgs e)
        {
            throw new NotImplementedException();
        }

        bool mh1_MouseWheelDown(MouseHookEventArgs e)
        {
            throw new NotImplementedException();
        }

        bool mh1_MouseButtonDown(MouseHookEventArgs e)
        {
            throw new NotImplementedException();
        }


        #region 注册鼠标热键
        MouseHook mh = new MouseHook();
        private void RegisterMouseKeys()
        {
            mh.MouseButtonDown += new MouseHookEventHandler(mh_MouseButtonDown);
            mh.MouseButtonUp += new MouseHookEventHandler(mh_MouseButtonUp);
            mh.Hook();           
        }

        bool mh_MouseButtonUp(MouseHookEventArgs e)
        {
            mh.MouseWheelUp -=mh_MouseWheelUp;
            mh.MouseWheelDown -= mh_MouseWheelDown;
            return true;
        }
        MouseHook mr = new MouseHook();
        bool mh_MouseButtonDown(MouseHookEventArgs e)
        {
            if (e.button ==Hook.MouseButton.Left)
            {
                mh.MouseWheelUp += new MouseHookEventHandler(mh_MouseWheelUp);
                mh.MouseWheelDown += new MouseHookEventHandler(mh_MouseWheelDown);

                mr.Hook();
                mr.MouseButtonDown += new MouseHookEventHandler(mr_MouseButtonDown);
                mr.MouseButtonUp += new MouseHookEventHandler(mr_MouseButtonUp);
            }
           
            return true;
        }

        bool mr_MouseButtonUp(MouseHookEventArgs e)
        {
            mr.MouseButtonDown -= mr_MouseButtonDown;
            mr.Unhook();
            return true;
        }

        bool mr_MouseButtonDown(MouseHookEventArgs e)
        {
            //if (e.button == Hook.MouseButton.Right)
            //{
            //    device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
            //}        
            return true;
        }

        bool mh_MouseWheelDown(MouseHookEventArgs e)
        {
            keybd_event((byte)Keys.ControlKey, 0, 0, 0);
            keybd_event((byte)Keys.Up, 0, 0, 0);
            keybd_event((byte)Keys.Up, 0, 0x2, 0);
            keybd_event((byte)Keys.ControlKey, 0, 0x2, 0);
            return true;
        }

        bool mh_MouseWheelUp(MouseHookEventArgs e)
        {
            keybd_event((byte)Keys.ControlKey, 0, 0, 0);
            keybd_event((byte)Keys.Down, 0, 0, 0);
            keybd_event((byte)Keys.Down, 0, 0x2, 0);
            keybd_event((byte)Keys.ControlKey, 0, 0x2, 0);
            return true;
        }
        #endregion

      
        //private void button1_Click(object sender, EventArgs e)
        //{          
        //    keybd_event((byte)Keys.ControlKey, 0, 0, 0);
        //    keybd_event((byte)Keys.Right, 0, 0, 0);
        //    keybd_event((byte)Keys.Right, 0, 0x2, 0);
        //    keybd_event((byte)Keys.ControlKey, 0, 0x2, 0);
        //}

        #region 注册dll
        [DllImport("User32.dll")] //模拟键盘事件
        static private extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtroInfo);
        #endregion
    }
}
